package com.starbaba.creditcard.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.base.common.util.StringUtils;
import com.google.gson.JsonObject;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.activityCommend.model.LoanProductChannelModel;
import com.starbaba.channelmanager.model.Product;
import com.starbaba.common.ResultJson;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.creditcard.model.Loan_Credit_Card_Info;
import com.starbaba.creditcard.model.Loan_Credit_Card_InfoVO;
import com.starbaba.creditcard.service.LoanCreditCareService;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.redis.JedisUtils;

@SuppressWarnings({"rawtypes","unchecked"})
public class LoanCreditCardAction extends BaseAction implements ModelDriven {

    private static final long serialVersionUID = 1L;
    
    @SuppressWarnings("deprecation")
    final BaseDao dao = new BaseDao(Constant.POOL_LIFE);
	private Loan_Credit_Card_InfoVO card_info;

	@Resource(name = "loanCreditCareServiceImpl")
	private LoanCreditCareService careservice;

	@Override
	public Object getModel() {
		if (card_info == null) {
			card_info = new Loan_Credit_Card_InfoVO();
		}
		return card_info;
	}

	public String show(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		PageResponse pageResponse = new PageResponse();
		try {
			paramsMap.put("productList", getProductList());
		} catch (AppException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public String getInfo() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		String id = (String) paramsMap.get("id");
		try {
			if (id != null)
				card_info = dao.get("select * from loan_credit_card_info where id =?", Loan_Credit_Card_InfoVO.class, id);

			if (card_info == null) {

				card_info = new Loan_Credit_Card_InfoVO();
			}

			paramsMap.put("model", card_info);
		} catch (AppException e) {
			e.printStackTrace();
		}

		List<LoanProductChannelModel> list = getChannelList();
		paramsMap.put("modelList", list);
		// List<LoanActivityModel> activityList = getActivityIDList();
		// paramsMap.put("activityList", activityList);
		try {
			List<Product> productList = getProductList();
			paramsMap.put("productList", productList);
		} catch (AppException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	public void saveCreditCard() throws IOException {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		card_info.setOperator(getUserVO().getUsername());
		if (!StringUtils.isEmpty(id)) {// 更新
			careservice.updateCreditCard(card_info);
		} else {// 新增
			careservice.saveCreditCard(card_info);

		}
		JsonObject result = new JsonObject();
		ResultJson resultJs = new ResultJson();
		resultJs.msg = "操作成功";
		result.add("result", resultJs.toJSON());
		sendJsonMessage(result.toString());
	}

	private void responseSuccess() {
		JsonObject result = new JsonObject();
		result.add("result", new ResultJson().toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	/**
	 * 信用卡列表
	 */
    public void getCardList() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		PageResponse pageResponse = new PageResponse();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();

		List list = careservice.getDataList(start, length, pageResponse, paramsMap);
		pageResponse.setAaData(list);
		pageResponse.setSEcho(pageRequest.getSEcho());

		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

    
	public void newSortPosition() throws AppException, IOException {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		// data: {'oldIndex':
		// oldIndex,'id':id,"newIndex":newIndex,"prdid":prdid,"platform":platform}
		String oldIndex = (String) paramsMap.get("oldIndex");// 老顺序
		String id = (String) paramsMap.get("id");// 更新的id
		String newIndex = (String) paramsMap.get("newIndex");// 新顺序

		@SuppressWarnings("unused")
        Integer oldIndexInt = Integer.parseInt(oldIndex);// 老顺序
		Integer newIndexInt = Integer.parseInt(newIndex);// 新顺序
		this.updateCpsPosition(id, newIndexInt);

		JsonObject result = new JsonObject();
		ResultJson resultJs = new ResultJson();
		resultJs.msg = "备注成功";
		result.add("result", resultJs.toJSON());
		sendJsonMessage(result.toString());
	}

	public void sortTab() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String prdidListStr = (String) paramsMap.get("prdSortList");
		String[] prdidList = prdidListStr.split("#");
		parsePageRequest();
		try {
			String sql = "update loan_credit_card_info c set c.position = ? where c.id = ?";
			for (int index = 0; index < prdidList.length; ++index) {
				Long id = Long.parseLong(prdidList[index]);
				dao.update(sql, index, id);
			}
			responseSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			responseError(e);
		}
	}

	/**
	 * 
	 *
	 * @Title responseSuccess
	 * @Description
	 *              <p>
	 *              返回错误信息
	 *              </p>
	 * 
	 * 
	 * @author zhengjunjie
	 * @dateTime 2015年10月16日 下午2:26:53
	 *
	 */
	private void responseError(Exception error) {
		StringWriter writer = new StringWriter();
		error.printStackTrace(new PrintWriter(writer, true));
		ResultJson resultJson = new ResultJson(-2, 0, writer.toString());
		JsonObject result = new JsonObject();
		result.add("result", resultJson.toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			LogService.error(e);
		}
	}

	public List<LoanProductChannelModel> getChannelList() {

		String sql = "select channel_code,channel_name from comm_product_channel";
		try {
			List<LoanProductChannelModel> list = dao.list(sql, LoanProductChannelModel.class, new Object[] {});

			return list;
		} catch (AppException e) {

			e.printStackTrace();
		}
		return null;
	}

	public List<Product> getProductList() throws AppException {
		//在基础上添加产品列表
		String sql = " SELECT DISTINCT prdid AS code,name AS kindname FROM comm_product_prdid";
		Product p = new Product();
		p.setCode(0);
		p.setKindname("通用");
		List<Product> productList = dao.list(sql, Product.class);
		productList.add(p);
		return productList;
	}
	
	
	private void updateCpsPosition(String id, Integer newIndexInt) throws AppException {
		String allSql = "select * from loan_credit_card_info  ORDER BY position asc";
		List<Loan_Credit_Card_Info> allList = dao.list(allSql, Loan_Credit_Card_Info.class, new Object[] {});

		String cpsSql = "select * from loan_credit_card_info where id = ?";
		Loan_Credit_Card_Info info = dao.get(cpsSql, Loan_Credit_Card_Info.class, id);

		List<Loan_Credit_Card_Info> newList = new ArrayList<Loan_Credit_Card_Info>();
		for (Loan_Credit_Card_Info vo : allList) {
			Long cpsid = vo.getId();
			if (!id.equals(String.valueOf(cpsid))) {
				newList.add(vo);
			}
		}
		if (newIndexInt == 0) {
			newList.add(0, info);
		} else if (newIndexInt > 0) {
			newList.add(newIndexInt - 1, info);
		} else {
			return;
		}

		int i = 1;
		for (Loan_Credit_Card_Info vo : newList) {
			vo.setPosition(i);
			dao.update(vo, new String[] { "id" });
			i++;
		}
	}

	/**
	 * 编辑活动
	 * @return
	 * @throws Exception
	 */
	public String editCard() throws Exception {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		String id = (String) paramsMap.get("id");
		try {
			card_info = dao.get("select * from loan_credit_card_info where id =?", Loan_Credit_Card_InfoVO.class, id);
		} catch (AppException e) {
			e.printStackTrace();
		}
		List<LoanProductChannelModel> list = getChannelList();
		paramsMap.put("modelList", list);
		paramsMap.put("model", card_info);
		try {
			List<Product> productList = getProductList();
			paramsMap.put("productList", productList);
		} catch (AppException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public void updateStatus() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		String status = (String) paramsMap.get("status");
		try {
			String sql = "update loan_credit_card_info c set c.status = ? where c.id= ? ";
			dao.update(sql, status, Long.parseLong(id));
			JsonObject result = new JsonObject();
			ResultJson resultJs = new ResultJson();
			resultJs.msg = "操作成功";
			result.add("result", resultJs.toJSON());
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			LogService.error(e);
		}
	}
	
	public void delRedis() {
        if(JedisUtils.exists("loan:credit_card_list")){
            JedisUtils.del("loan:credit_card_list");
        }
        if(JedisUtils.exists("loan:activity_credit_list")){
            JedisUtils.del("loan:activity_credit_list");
        }
        responseSuccess();
    }
}
